package com.example.demo.demos.exportUtils;


import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class ExportResult {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExportResult.class);

    private File exportedFile;

    ExportResult(File exportedFile) {
        this.exportedFile = exportedFile;
    }

    public File getExportedFile() {
        if (null == this.exportedFile) {
            throw new NullPointerException("exportedFile 为 null");
        }
        return exportedFile;
    }

    public void download(HttpServletRequest request, HttpServletResponse response) {
        File exportedFile = getExportedFile();
        // 用于清除首部的空白行
        response.reset();
        response.setContentType("application/x-download; charset=utf-8");
        setFileDownloadHeader(request, response, this.exportedFile.getName());
        doDownload(response, exportedFile);
    }

    private void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String filename) {
        //获取浏览器信息
        String ua = request.getHeader("USER-AGENT");
        //转成UserAgent对象
        UserAgent userAgent = UserAgent.parseUserAgentString(ua);
        //获取浏览器信息
        Browser browser = userAgent.getBrowser();
        //浏览器名称
        String browserName = browser.getName();
        String encodedFilename;
        try {
            encodedFilename = URLEncoder.encode(filename, "UTF8");
            if (StringUtils.contains(browserName, "Internet Explorer")) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
            } else if (StringUtils.contains(browserName, "Chrome") || StringUtils.contains(browserName, "Firefox")) {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFilename);
            } else {// 其他浏览器
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFilename + "\"");
            }
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    private void doDownload(HttpServletResponse response, File exportedFile) {
        OutputStream os = null;
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        FileInputStream exportedFileInputStream = null;
        try {
            exportedFileInputStream = new FileInputStream(exportedFile);
            response.addHeader("content-length", exportedFileInputStream.available() + "");
            os = response.getOutputStream();
            bis = new BufferedInputStream(exportedFileInputStream);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            os.flush();
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        } finally {
            if (exportedFileInputStream != null) {
                try {
                    exportedFileInputStream.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
            // 下载完成后删除临时文件
            if (exportedFile.exists()) {
                File exportedFileDir = exportedFile.getParentFile();
                FileUtils.deleteDir(exportedFileDir);
            }
        }
    }
}